/*!
 @header ConsigneeFormViewController.h
 @author 王 文彬
 @version 1.0.0 2013/01/30 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "ConsigneeFormViewController.h"
#import "Config.h"
#import "Helper.h"
#import "JMFBase.h"

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：1、所有textfield未开始编辑时都是无边框的。

//            2、根据_consignee是否为nil来判断用户是否是添加新地址。当用户是添加新地址时，view中是没有任何按钮的；
//            当用户是查看或修改地址信息时，如果此地址不是默认地址，那么就会存在删除按钮和设置默认地址按钮，否则只有删除按钮。
//
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface ConsigneeFormViewController ()

@end

@implementation ConsigneeFormViewController

@synthesize dismissMode = _dismissMode;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithConsignee:(NSDictionary *)consignee
{
    self = [super init];
    if (self) {
        _consignee = consignee;
        _dismissMode = consignee ? false : true;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    self.title = _consignee ? _L(@"vc_title_010") : _L(@"vc_title_009");  //修改地址：增加地址
    
    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //导航按钮右按钮：保存
    UIButton* saveButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
    [saveButton addTarget:self action:@selector(saveButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    
    //背景框
    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 30, 300, 204)];
    bgImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_008@2x" ofType:@"png"]];
    bgImageView.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:bgImageView];
    
    //
    _nameField = [[UITextField alloc] initWithFrame:CGRectMake(110, 36, 180, 24)];
//    _nameField.borderStyle = UITextBorderStyleRoundedRect;
    _nameField.font = _SYS_FONT_004;
    _nameField.placeholder = _L(@"holder_02");      //2到8个字
    _nameField.returnKeyType = UIReturnKeyDone;
    _nameField.delegate = (id)self;
    _nameField.backgroundColor = [UIColor whiteColor];
    [_nameField addTarget:self action:@selector(fieldTouchEvent:) forControlEvents:UIControlEventAllTouchEvents];
    [self.view addSubview:_nameField];
    

    _mobileField = [[UITextField alloc] initWithFrame:CGRectMake(110, 70, 180, 25)];
//    _mobileField.borderStyle = UITextBorderStyleRoundedRect;
    _mobileField.keyboardType = UIKeyboardTypePhonePad;
    _mobileField.font = _SYS_FONT_004;
    _mobileField.returnKeyType = UIReturnKeyDone;
    _mobileField.delegate = (id)self;
    _mobileField.placeholder = _L(@"holder_03");    //请输入你常用的电话号码
    _mobileField.backgroundColor = [UIColor whiteColor];
    [_mobileField addTarget:self action:@selector(fieldTouchEvent:) forControlEvents:UIControlEventAllTouchEvents];
    
    [self.view addSubview:_mobileField];

    
    _zipCodeField = [[UITextField alloc] initWithFrame:CGRectMake(110, 107, 180, 26)];
//    _zipCodeField.borderStyle = UITextBorderStyleRoundedRect;
    _zipCodeField.returnKeyType = UIReturnKeyDone;
    _zipCodeField.font = _SYS_FONT_004;
    _zipCodeField.keyboardType = UIKeyboardTypeNumberPad;
    _zipCodeField.delegate = (id)self;
    _zipCodeField.placeholder = _L(@"holder_04");      //请输入邮政编码
    _zipCodeField.backgroundColor = [UIColor whiteColor];
    [_zipCodeField addTarget:self action:@selector(fieldTouchEvent:) forControlEvents:UIControlEventAllTouchEvents];

    [self.view addSubview:_zipCodeField];
    
    
    _regionField = [[UITextField alloc] initWithFrame:CGRectMake(110, 145, 180, 25)];
//    _regionField.borderStyle = UITextBorderStyleRoundedRect;
    _regionField.tag = 88;
    _regionField.font = _SYS_FONT_004;
    _regionField.delegate = (id)self;
    _regionField.placeholder = _L(@"holder_05");       //请选择地区
    _regionField.backgroundColor = [UIColor whiteColor];
    [_regionField addTarget:self action:@selector(fieldTouchEvent:) forControlEvents:UIControlEventAllTouchEvents];

    [self.view addSubview:_regionField];
    
    _addressField = [[UITextField alloc] initWithFrame:CGRectMake(110, 190, 180, 25)];
//    _addressField.borderStyle = UITextBorderStyleRoundedRect;
    _addressField.tag = 99;
    _addressField.font = _SYS_FONT_004;
    _addressField.returnKeyType = UIReturnKeyDone;
    _addressField.delegate = (id)self;
    _addressField.placeholder = _L(@"holder_06");      //请添加详细地址
    _addressField.backgroundColor = [UIColor whiteColor];
    [_addressField addTarget:self action:@selector(fieldTouchEvent:) forControlEvents:UIControlEventAllTouchEvents];

    [self.view addSubview:_addressField];
    
    _removeButton = [[UIButton alloc] initWithFrame:CGRectMake(10, _SYS_FRAME_HEIGHT - 44 - 20 - 44 - 10 - 44, 300, 44)];
    _removeButton.titleLabel.font = _SYS_FONT_009;
    [_removeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_removeButton setTitle:_L(@"btn_delete_01") forState:UIControlStateNormal];   //删除联系地址
    [_removeButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_007_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_removeButton addTarget:self action:@selector(removeButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    _removeButton.hidden = true;
    [self.view addSubview:_removeButton];
    
    
    _statusButton = [[UIButton alloc] initWithFrame:CGRectMake(10, _SYS_FRAME_HEIGHT - 44 - 20 - 44, 300, 44)];
    _statusButton.titleLabel.font = _SYS_FONT_009;
    [_statusButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_statusButton setTitle:_L(@"btn_set_01") forState:UIControlStateNormal];     //设置成默认收货地址
    [_statusButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_006_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_statusButton addTarget:self action:@selector(statusButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    _statusButton.hidden = true;
    [self.view addSubview:_statusButton];
    
    
    //视图载入完后刷新一下各组件状态，因为有可能Consignee已经被设置了
    if (_consignee) {
        _nameField.text = [_consignee objectForKey:@"consignee"];
        _mobileField.text = [_consignee objectForKey:@"mobile"];
        _zipCodeField.text = [_consignee objectForKey:@"zipCode"];
        _regionField.text = [_consignee objectForKey:@"region"];
        _addressField.text = [_consignee objectForKey:@"address"];
        
        _removeButton.hidden = false;
        _statusButton.hidden = [[_consignee objectForKey:@"status"] boolValue];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 返回按钮流程

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    BOOL modifyFlag = false;
    if (![_consignee[@"consignee"] isEqualToString:_nameField.text] ||
        ![_consignee[@"mobile"] isEqualToString:_mobileField.text] ||
        ![_consignee[@"zipCode"] isEqualToString:_zipCodeField.text] ||
        ![_consignee[@"region"] isEqualToString:_regionField.text] ||
        ![_consignee[@"address"] isEqualToString:_addressField.text]) {
        modifyFlag = true;
    }
    
    if ((_consignee == nil && (_nameField.text.length > 0 || _mobileField.text.length > 0 || _zipCodeField.text.length > 0 || _regionField.text.length > 0 || _addressField.text.length > 0))
        || (_consignee != nil && modifyFlag)) {
        
        NSString* alertString = _consignee ? _L(@"alert_93") : _L(@"alert_92");
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        alertView.tag = 2;  //与删除按钮的警告框区别
        [alertView show];
    }
    else {
        if (_dismissMode) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
}


#pragma mark - 自定义事件
/*!
 @abstract 保存按钮事件
 */
- (void)saveButtonEvent
{
    JSONRequest* request;
    if (_consignee == nil) {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CONSIGNEE_ADD];
    }
    else {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CONSIGNEE_CHANGE_INFO];
        [request setValue:[NSString stringWithFormat:@"%i", [_consignee[@"id"] integerValue]] forParameter:@"consigneeId"];
    }

    [request setValue:_nameField.text forParameter:@"name"];
    [request setValue:_mobileField.text forParameter:@"mobile"];
    [request setValue:_zipCodeField.text forParameter:@"zipCode"];
    [request setValue:_regionField.text forParameter:@"region"];
    [request setValue:_addressField.text forParameter:@"address"];
    [request setValue:@"76504580" forParameter:@"tel"];

    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_05");     //正在保存
    [request asynchronous];
}

/*!
 @abstract 设置默认地址按钮事件
 */
- (void)statusButtonEvent
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CONSIGNEE_CHANGE_DEFAULT];
    [request setValue:[NSString stringWithFormat:@"%i", [[_consignee objectForKey:@"id"] integerValue]] forParameter:@"consigneeId"];
    NSDictionary* dict = [request synchronous];

    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {
        if (_dismissMode) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

/*!
 @abstract 删除按钮事件
 */
- (void)removeButtonEvent
{
    UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:_L(@"alert_05") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];   //确定是否要删除此地址
    alerView.tag = 1;
    [alerView show];
}

/*!
 @abstract textfield被点击
 */
- (void)fieldTouchEvent:(id)sender
{
    _nameField.borderStyle = UITextBorderStyleNone;
    _mobileField.borderStyle = UITextBorderStyleNone;
    _zipCodeField.borderStyle = UITextBorderStyleNone;
    _regionField.borderStyle = UITextBorderStyleNone;
    _addressField.borderStyle = UITextBorderStyleNone;
    
    UITextField* currentField = sender;
    currentField.borderStyle = UITextBorderStyleRoundedRect;
}

#pragma mark - 私有方法

/*!
 @abstract 键盘消失时重设view的frame
 */
- (void)recoverView
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    //每次都要重置视图，否则先点击底部field视图上移后，再点击上面的field，点击返回按钮后，视图会停留在移动后的高度
    
    [self recoverView];
    
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //点击后删除之前的PickerView
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UICustomPickerView class]]) {
            [view removeFromSuperview];
        }
    }
    
    if (textField.tag == 99) {
        CGRect frame = textField.frame;
        int offset = frame.origin.y + 252 - (self.view.frame.size.height - 252);//键盘高度216
        
        NSTimeInterval animationDuration = 0.30f;
        [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        float width = self.view.frame.size.width;
        float height = self.view.frame.size.height;
        if(offset > 0)
        {
            CGRect rect = CGRectMake(0.0f, -60,width,height);
            self.view.frame = rect;
        }
    }else if (textField.tag == 88) {
        
        [_nameField resignFirstResponder];
        [_mobileField resignFirstResponder];
        [_zipCodeField resignFirstResponder];
        [_addressField resignFirstResponder];
        
        //点击后删除之前的PickerView
        for (UIView *view in self.view.subviews) {
            if ([view isKindOfClass:[UICustomPickerView class]]) {
                [view removeFromSuperview];
            }
        }
        _customPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
        _customPickerView.tag = 96;
        _customPickerView.delegate = self;
        _customPickerView.location = textField.text;
        _customPickerView.hzAreaPickerStyle = HZAreaPickerWithStateAndCityAndDistrict;
        _customPickerView.areaPickerOption = HZAreaPickerInitNormalOption;
        
        [self.view addSubview:_customPickerView];
        [_customPickerView pickerShow:UICustomPickerViewAreaType];
        return NO;
    }
    
    [UIView commitAnimations];
    return YES;
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    //每次都要重置视图，否则先点击底部field视图上移后，再点击上面的field，点击返回按钮后，视图会停留在移动后的高度
    [self recoverView];
}

#pragma mark - CustomPickerView delegate
- (void)customPickerView:(UICustomPickerView *)customPickerView areaStringReceived:(NSString *)area
{
    _regionField.text = area;
    [_regionField resignFirstResponder];
}

- (void)customPickerViewDidDismiss:(UICustomPickerView *)customPickerView
{
    
    [_regionField resignFirstResponder];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        if (_dismissMode) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}


#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CONSIGNEE_REMOVE];
            [request setValue:[NSString stringWithFormat:@"%i", [[_consignee objectForKey:@"id"] integerValue]] forParameter:@"consigneeId"];
            NSDictionary* dict = [request synchronous];
            
            JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
            if (jmf.status == JMStatusSucceed) {
                
                if (_dismissMode) {
                    [self.navigationController dismissModalViewControllerAnimated:true];
                }
                else {
                    [self.navigationController popViewControllerAnimated:true];
                }
            }
            else {
                [Helper easyShowJMFStatus:jmf];
            }
        }
    }
    else if (alertView.tag == 2 && buttonIndex == 1) {
        
        if (_dismissMode) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_nameField resignFirstResponder];
    [_mobileField resignFirstResponder];
    [_zipCodeField resignFirstResponder];
    [_regionField resignFirstResponder];
    [_addressField resignFirstResponder];
    
}
@end
